﻿if(!window.WebSocket && window.MozWebSocket)
	window.WebSocket = window.MozWebSocket;
if(!window.WebSocket)
	alert("No Support ");
//WebSocket状态监测，重连，测试，保持连接的总循环
var WebRTCInterval = null;
//连接循环测试时间(mm)
var WEBRTC_WAIT_TIMES = 5000;
//测试消息发送间隔(秒)
var WEBRTC_SEND_NEEDREPLY_TIMES = WEBRTC_WAIT_TIMES * 6;

var listenChatMsg = null; //定义侦听消息回传

//派发服务器(WebSocket)连接设置相关
var RTCConnectSetting = {
	//总的循环次数，用于计时
	loopCounts: 0,
	//测试消息的发送Flag
	wait_test_reply: false
};
//连接检查状态初期化
function RTCConnectSettingInit() {
	RTCConnectSetting.loopCounts = 0;
	RTCConnectSetting.wait_test_reply = false;
}

function WebRTCConnect(UserInfo) {
	try {
		//检查是否已经登录
		if(UserInfo.userid !== null &&
			UserInfo.userid != "") {
			//检查socket状态
//			console.log(rtc);
			if(rtc._socket !== undefined &&
				rtc._socket !== null &&
				rtc._socket.readyState === 1) {
					
				if(RTCConnectSetting.wait_test_reply == false) {
					//正常的情况，每隔一定时间发送测试连接的消息
					if(RTCConnectSetting.loopCounts * WEBRTC_WAIT_TIMES %
						WEBRTC_SEND_NEEDREPLY_TIMES == 0) {
						//发测试消息，保持连接
						var testMsg = {
							"eventName": "test_connect",
							"data": { "UserID": UserInfo.userid }
						};
						rtc._socket.send(JSON.stringify(testMsg));
						RTCConnectSetting.wait_test_reply = true;
					}
				} else {
					//没有回复的的情况，说明Socket不通,重连
					setConnect(UserInfo);
				}
				RTCConnectSetting.loopCounts++;
			} else {
				//状态不正确，重新连接
				setConnect(UserInfo);
			}
		} else {
			//关闭连接
			CloseWebRTCSocket();
		}
	} catch(ex) {
		console.log("websocket连接异常");
	}
}

//关闭WebSocket
function CloseWebRTCSocket() {
	try {
		if(rtc._socket != null &&
			rtc._socket != undefined) {
			rtc._socket.close();
			rtc._socket
		}
	} catch(e) {

	}
}
//连接WebSocket并设置消息处理函数
function setConnect(UserInfo) {
	//初期化
	RTCConnectSettingInit();
	//连接
	rtc.connect(UserInfo.dispathURL);
	
	//监听连接成功事件
	rtc.on("connect", function() {
		//收到连接成功
		joinRoom(UserInfo);
		//收到消息处理
		if(listenChatMsg != null)
			listenChatMsg();

	});
	//监听收到消息事件
	rtc.on("receive_chat_msg", function(data) {
		//收到消息处理
		if(listenChatMsg != null)
			listenChatMsg(data);
	});
	//连接测试消息回复事件
	rtc.on("test_connect", function() {
		//收到测试消息返回
		RTCConnectSetting.wait_test_reply = false;
	});
	//Kick监听事件,KICK表示用户退出登录了
	rtc.on("user_kick", function() {
		//RefreshPage();
	});
	//SystemKick监听事件
	rtc.on("system_kick", function() {
		//RefreshPage();
	});
	//need_join_room
	rtc.on("need_join_room", function() {
		joinRoom(UserInfo);
	});

}
//加入房间的处理
function joinRoom(UserInfo) {
	try {
		if(rtc._socket != null &&
			rtc._socket != undefined) {
			rtc._socket.send(JSON.stringify({
				"eventName": "join_room",
				"data": {
					"room": UserInfo.userid,
					"LoginCode": UserInfo.logincode
				}
			}));
		}
	} catch(e) {

	}
}//初始化消息侦听
function initListenMsg(callback,$scope){
//	if(listenChatMsg==null)
	listenChatMsg = callback;
}
